<script setup lang="ts">
import {onBeforeMount, ref} from 'vue';
import { useRoute } from 'vue-router';
import VMdPreview from '@kangc/v-md-editor/lib/preview';
import {watch} from "vue";
import {fetchWebInformation} from "@/static/utils/fetch_ctf_web_info";
import {useUserStore} from "@/stores/userStore";


// 获取当前路由
const route = useRoute();
const markdownText = ref('');

// 动态加载Markdown文本
const loadMarkdown = async (filename) => {
  // 根据后端数据动态创建markdownFiles映射
  await fetchWebInformation()
  const userStore = useUserStore()
  const ctfWebData = userStore.ctfWebData

  console.log(ctfWebData)

  const markdownFiles = {};
  for (const item of ctfWebData) {
    // console.log(item);
    markdownFiles[item.title] = `/public/markdown/${item.title}.md?raw`;
  }

  const path = markdownFiles[filename];
  if (path) {
    const response = await fetch(path);
    markdownText.value = await response.text();
  } else {
    markdownText.value = '攻略组正在加班写WriteUp ... ...';
  }

  // 在组件挂载前加载Markdown文本
  onBeforeMount(() => {
    loadMarkdown(route.params.filename);
  });
};

// 监听路由参数的变化并重新加载Markdown文本
watch(() => route.params.filename, (newFilename) => {
  loadMarkdown(newFilename);
}, { immediate: true });

</script>

<template>
  <VMdPreview :text="markdownText" />
</template>

<style scoped>
:deep(.vuepress-markdown-body) {
  background-color: #23242a;
}

:deep(.vuepress-markdown-body:not(.custom)) {
  padding: 0;
  font-size: 18px;
  color: #d9d9d9;
}

:deep(.vuepress-markdown-body) code {
  background-color: #000000;
  color: #64ffa9;
  border-radius: 10px;
  margin: 0 8px;
}

:deep(.vuepress-markdown-body) p {
  margin: 10px;
  user-select: none;
}

:deep(.vuepress-markdown-body) h1 {
  color: #ffffff;
  font-size: 38px;
  letter-spacing: 2px;
}

:deep(.vuepress-markdown-body) h3 {
  color: #f44c4c;
}

:deep(.vuepress-markdown-body) img {
  user-select: none;
  cursor: default;
}

</style>